#include "ServerMessageReceiver.h"
#include "NetworkEvent.h"
#include "ClientConnectNetworkEvent.h"
#include "NetworkException.h"
#include "NetworkWrapper.h"

MessageReceiver::MessageReceiver(const TCPsocket& socket)
        : socket(socket)
{
}

MessageReceiver::~MessageReceiver()
{
}

void MessageReceiver::cleanUp()
{
    NetworkWrapper::closeSocket(socket);
    socket = NULL;
}

NetworkEvent::Header MessageReceiver::fetchHeader()
{
    NetworkEvent::Header header;
    NetworkWrapper::receiveFrom(socket, &header, sizeof(header));
    return header;
}

void* MessageReceiver::fetchData(NetworkEvent::Header& header)
{
    void* data = malloc(header.sizeOfData);
    NetworkWrapper::receiveFrom(socket, data, header.sizeOfData);
    return data;
}

void MessageReceiver::mainLoop()
{
    void* data = NULL;
    NetworkEvent::Header header;
    try
    {
        header = fetchHeader();
        if (header.sizeOfData > 0)
        {
            data = fetchData(header);
        }
    }
    catch (NetworkException& e)
    {
        quit(false);
        free(data);
        data = createDisconnectEvent(header);
    }

    pushEvent(header, data);
}

void MessageReceiver::send(void* data, size_t size)
{
    NetworkWrapper::sendTo(socket, data, size);
}
